<?php


namespace app\app\controller;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Db;

class Index extends Base
{
    public $accessKeyId = "LTAI4G5dGuDFgvzjm8wSqReQ";
    public $accessKeySecret = "JSyjc0KA3o1aesHivcuDUZoQicXJJe";

    public function __construct()
    {
        parent::__construct();
    }

    //赛事页广告
    public function saishiad()
    {
        $input = input();

        $order = 'saishishunxu asc, id desc';
        //开屏
        $where['adtype'] = 0;
        $where['status'] = 1;
        $where['type_id'] = $input['type_id'];
        $res = model('Ad')->listAll($where, $order);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    //轮播页广告
    public function lunboad()
    {
        $input = input();

        $order = 'lunboshunxu asc, id desc';
        //开屏
        $whereOr = ['adtype' => 1, 'from' => 1];
        $where['status'] = 1;
        $res = model('Ad')->listAllOr($whereOr, $order, $where);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    //列表页广告
    public function liebiaoad()
    {
        $input = input();

        $order = 'id desc';
        //开屏
        $where['adtype'] = 2;
        $where['status'] = 1;
        $where['istuijian'] = $input['istuijian'];
        $where['mokuai_id'] = $input['mokuai_id'];
        $res = model('Ad')->listAll($where, $order);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    //详情页广告
    public function xiangqingad()
    {
        $order = 'id desc';
        //开屏
        $where['adtype'] = 4;
        // $where['status'] = 1;
        $res = model('Ad')->listAll($where, $order);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    //个人中心广告
    public function myad()
    {
        $order = 'id desc';
        //开屏
        $where['adtype'] = 5;
        // $where['status'] = 1;
        $res = model('Ad')->listAll($where, $order);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    //开屏广告
    public function kaipingad()
    {
        $order = 'id desc';
        //开屏
        $where['adtype'] = 3;
        // $where['status'] = 1;
        $res = model('Ad')->listAll($where, $order);
        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function delDirAndFile($path, $delDir = false)
    {
        if (is_array($path)) {
            foreach ($path as $subPath) {
                $this->delDirAndFile($subPath, $delDir);
            }
        }
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != "." && $item != "..") {
                        is_dir("$path/$item") ? $this->delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
                    }
                }
                closedir($handle);
                if ($delDir) {
                    return rmdir($path);
                }
            }
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return false;
            }
        }
    }


    public function removefiledata()
    {
        $input = input();

        $id = $input['id'];

        Db::name('Vod')->where(['vod_id' => $id])->update(['is_cache' => 0]);

        // 创建id目录
        $path = $_SERVER['DOCUMENT_ROOT'] . "/upload/m3u8/" . $id;
        //判断目录存在否，存在给出提示，不存在则创建目录
        if (is_dir($path)) {
            // echo "目录 $path 存在";
            //删掉整个目录
            $this->delDirAndFile($path, true);
        }

        $this->success();
    }

    public function musavedata()
    {
        $input = input();

        $data = $input['d'];

        $id = $input['id'];
        $name = $input['name'];
        $fenjiindex = $input['fenjiindex'];
        $index = $input['index'] + 1 + $fenjiindex;

        $path = $_SERVER['DOCUMENT_ROOT'] . "/upload/m3u8/" . $id;
        //判断目录存在否，存在给出提示，不存在则创建目录
        if (!is_dir($path)) {
            mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
        }

        //缓存第一个ts文件
        $path_ts = $_SERVER['DOCUMENT_ROOT'] . "/upload/m3u8/" . $id . "/1";
        $file_url_hou = "/upload/m3u8/" . $id . "/" . $index . "_" . $name . ".m3u8";
        $file_url = $_SERVER['DOCUMENT_ROOT'] . $file_url_hou;

        if (file_exists($file_url)) {
            echo json_encode(['data' => $file_url, "name" => $name, "res" => 1000]);
            exit;
        }

        //判断目录存在否，存在给出提示，不存在则创建目录
        if (is_dir($path_ts)) {
            // echo "目录 $path_ts 存在";
        } else {
            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
            $res_ts = mkdir(iconv("UTF-8", "GBK", $path_ts), 0777, true);
            if ($res_ts) {
                // echo "目录 $path_ts 创建成功";
            } else {
                // echo "目录 $path_ts 创建失败";
            }
        }

        $indexitem = 0;
        if (!empty($data)) {
            foreach ($data as $key => $v) {
                if ((strstr($v, "http") !== false) && !(strpos($v, "#") !== false)) {
                    if ($indexitem < 1) {
                        //保存前3个ts
                        $itemdata = file_get_contents($v);
                        $res = file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/upload/m3u8/" . $id . "/1/" . basename($v), $itemdata);
                        $data[$key] = "1/" . basename($v);
                        $indexitem++;
                    }
                }
            }
        }
        // echo json_encode(['ddd' => implode("\r\n", $data)]);exit;

        //保存m3u8数据
        $res = file_put_contents($_SERVER['DOCUMENT_ROOT'] . $file_url_hou, implode("\r\n", $data));
        if ($res > 0) {
            $realurl = 'http://' . $_SERVER['HTTP_HOST'] . $file_url_hou;
            Db::name('Vod')->where(['vod_id' => $id])->update(['is_cache' => 1]);
            echo json_encode(['data' => $realurl, "name" => $name, "res" => $res]);
        }
    }

    public function errorm3u8log()
    {
        $input = input();
        $id = $input['id'];
        $name = $input['name'];
        Db::name('m3u8cache')->where(['vod_id' => $id])->delete();
        $res = Db::name('m3u8cache')->insert(['vod_id' => $id, 'name' => $name]);
        if ($res) {
            echo json_encode(['status' => 1]);
            exit;
        }
    }

    function posturl($url, $data)
    {
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);

        // db('tt')->insert([
        //     'tt' => $output
        // ]);
        curl_close($curl);
        return json_decode($output, true);
    }

    public function updatem3u8cachelog()
    {
        //和数据表做比对
        $input = input();
        $id = $input['id'];
        $len = (int)$input['len'];

        $data = ['status' => false];
        $res = Db::name('m3u8cache_log')->where(['vod_id' => $id])->update(['len' => $len]);

        if ($res) {
            $data = ['status' => true];
        }

        echo json_encode($data);
    }

    public function saveopenadlog()
    {
        $input = input();
        $data['adtype'] = $input['adtype'];
        $data['app_id'] = $input['app_id'];
        $data['app_name'] = $input['app_name'];
        $data['device_name'] = $input['device_name'];
        $data['device_id'] = $input['device_id'];
        $data['app_version'] = $input['app_version'];
        $data['key_name'] = $input['key_name'];

        $data['ctime'] = time();

        if (!empty($data['app_id'])) {
            if(in_array($data['adtype'],[1,2,3,4])) {
                $data['memo'] = '广告关闭';
                //解除广告
                $rows = \db('device')->where('app_id', $data['app_id'])->where('device_id', $data['device_id'])->update(['is_need_updated' => 0]);
                if ($rows > 0) {
                    sendDingding('用户 ' . $data['device_name'] . '[' . $data['app_name'] . '](' . $data['device_id'] . ') 正常浏览', 'updatedevice');
                }
            }
            $res = Db::name('openadlog')->insert($data);

            //处理积分
            $appInfos = db('banben')->where('app_id',$data['app_id'])->find();
//        dump($appInfos);
            if($data['adtype']==2 && !empty($appInfos) && $appInfos['is_ad_to_points']>0){
                $points = $appInfos['is_ad_to_points'];
//            $pointsToday = \db('points')->where('app_id',$data['app_id'])->where('device_id',$data['device_id'])->where('date',date('Y-m-d',$data['ctime']))->where('type','ad')->sum('points');
//            dump($pointsToday);exit;
                if($points>0) {
                    addLog($appInfos['app_id'], $data['device_id'], $points, '看广告得' . $points . '积分', 'ad', date('Y-,m-d', $data['ctime']), $data['ctime']);
                }
                $totalPoints = \db('device')->where('app_id',$data['app_id'])->where('device_id',$data['device_id'])->value('points');
                $msg="观看广告获得".$points.'积分';
            }else{
                $points=0;
                $totalPoints = 0;
                $msg='';
            }
            //得到今日该设备广告数量
            $count = dealDeviceDate($data);

            $map['timeid'] = date('Ymd');
            $map['app_name'] = $input['app_name'];
            try {
                \db('m3u8_guanggaotongji')->insertGetId($map);
            } catch (\Exception $e) {

            }
            if ($input['adtype'] == '1') {
                $a = \db('m3u8_guanggaotongji')->where($map)->setInc('kaiping', 1);
            }
            if ($input['adtype'] == '2') {
                $a = \db('m3u8_guanggaotongji')->where($map)->setInc('quanping', 1);
            }
            if ($input['adtype'] == '3') {
                $a = \db('m3u8_guanggaotongji')->where($map)->setInc('jili', 1);
            }
            if ($input['adtype'] == '4') {
                $a = \db('m3u8_guanggaotongji')->where($map)->setInc('banner', 1);
            }

            $this->posturl("http://yingshi.acorntimes.com/app.php/state/saveopenadlog", $input);
            $this->success($msg, ['data' => $res,'points'=>$points,'totalPoints'=>$totalPoints,'count'=>$count]);
        }
        $this->error($msg);
    }

    public function saveopenadlogKaiqi()
    {
        $input = input();
        $data['adtype'] = $input['adtype'];
        $data['app_id'] = $input['app_id'];
        $data['app_name'] = $input['app_name'];
        $data['device_id'] = $input['device_id'];
        $data['device_name'] = $input['device_name'];
        $data['app_version'] = $input['app_version'];
        $data['key_name'] = $input['key_name'];
        $data['vod_id'] = $input['vod_id'];
        $data['vod_name'] = $input['vod_name'];
        $data['zhibo_id'] = $input['zhibo_id'];
        $data['zhibo_name'] = $input['zhibo_id'] > 0 ? ("[" . $input['zhibo_name'] . "]" . $input['zhibo_qiudui']) : '';
        $data['memo'] = '广告展示';
        $data['ctime'] = time();

        if (!empty($input['app_id'])) {
            $res = Db::name('openadlog')->insert($data);
        }
        $data['is_show']=true;//用于广告统计显示数据
        dealDeviceDate($data);
        $this->success("", ['data' => $res]);
    }

    public function checkbanbennew()
    {
        //和数据表做比对
        $input = input();
        $keyname = $input['keyname'];
        $type = $input['type'];
        $device_id = $input['device_id'];
        $app_id = $input['app_id'];
        if ($type == 1) {

        }
        $res = Db::name('banben')->where(['keyname' => $keyname])->find();
        $shebeidata = Db::name('device')->where(['device_id' => $device_id, 'app_id' => $app_id])->field('is_need_updated')->find();
        if (empty($shebeidata)) {
            $shebeidata['is_need_updated'] = 0;
        } else {
            $ip = $shebeidata['first_ip'];
            if (empty($ip)) {
                $firstLog = db('state')->where('device_id', $device_id)->order('time_added', 'asc')->field('ip')->find();
//            dump(db('state')->getLastSql());
//            dump($firstLog);
                if (!empty($firstLog)) {
                    //有观影记录第一次ip记录使用第一次访问的IP记录
                    $firstIp = $firstLog['ip'];
                } else {
                    //没有过观影记录那么 就是当前IP
                    $firstIp = $shebeidata['ip'];;
                }
                \db('device')->where('device_id', $device_id)->where('can_jump', 0)->update([
                    'first_ip' => $firstIp
                ]);
                $ip = $firstIp;
            }
        }

//        $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
//            $ip ='39.75.150.116';//淄博市
//        dump($ip);
        if (empty($ip)) {
            $ip = get_client_ip(0, true);
        }
        if ($res) {
            //ios检查ip地址信息
            $ipInfo = $this->getIpInfo($ip, 'app/index/checkbanbennew');
//            dump($ipInfo);
            if (isset($ipInfo['success'])) {
                $ipInfo = $ipInfo['ipInfo'];
                $res['heimingdanshengshi'] = array_filter(explode(',', $res['heimingdanshengshi']));
                $needChangeurl = false;
                if (strtolower($ipInfo['guo_code']) !== 'cn') {
                    $needChangeurl = true;
                } elseif (!empty($ipInfo['shi']) || !empty($ipInfo['sheng'])) {
                    if (in_array($ipInfo['sheng'], $res['heimingdanshengshi']) || in_array($ipInfo['shi'], $res['heimingdanshengshi'])) {
                        $needChangeurl = true;
                    }
                }

                if ($needChangeurl) {
                    $res['change'] = 1;
                    //替换跳转地址
                    if (!empty($res['heimingdaniosurl']))
                        $res['iosurl'] = $res['heimingdaniosurl'];
                    if (!empty($res['heimingdanipadurl']))
                        $res['ipadurl'] = $res['heimingdanipadurl'];
                    if (!empty($res['heimingdananzhuourl'])) {
                        $res['anzhuourl'] = $res['heimingdananzhuourl'];
                    }
                    if ($input['system_type'] !== 'ios') {
                        $res['anzhuourl'] = '';
                        $res['status'] = 3;
                        $res['msg']="应用维护中.....";
                    }
                }
            }
            unset($res['heimingdanshengshi']);
            unset($res['heimingdaniosurl']);
            unset($res['heimingdanipadurl']);
            unset($res['heimingdananzhuourl']);
            unset($res['heimingdan_jumpshengshi']);

            unset($res['jpush_app_key']);
            unset($res['jpush_master_secret']);
            unset($res['can_push']);
            unset($shebeidata['first_ip']);
            unset($shebeidata['ip']);
            //如果广告关闭 这个用户是需要升级的用户那么此处不处理 在设置升级用户的地方进行限制 如果是广告没有开启，那么就不把她设置为升级用户。
            $data = ['data' => ['banben' => $res, 'shebeidata' => $shebeidata], 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function checkDisabledAppId()
    {
        $input = input();
        $keyname = $input['keyname'];
        $device_id = $input['device_id'];
        $app_id = $input['app_id'];
        $disabledAreas = getDisableAreasByAppId($app_id);
        if ($disabledAreas === false) {
            return '';
        }

        $res = array (
            'id' => 11,
            'display' => 1,
            'can_push' => 1,
            'sort' => 2,
            'appname' => '谷仓影视',
            'banbenhao' => 'v1.0',
            'iosurl' => 'https://apps.apple.com/cn/app/id1546969964',
            'anzhuourl' => 'http://m.saok.xyz',
            'status' => 2,
            'keyname' => $keyname,
            'ctime' => 1608693911,
            'neirong' => '温馨提示： 
系统检测到当前app有新的更新。
请重启app完成更新， 
或点击下方“立即更新”安装最新版本。 
体验极速观影！',
            'app_id' => '1111',
            'jpush_app_key' => '22859067e88ed0ccf3f861c3',
            'jpush_master_secret' => '88fe66297b913eb2a2aee7b3',
            'detailneirong' => '温馨提示： 
系统检测到当前app有新的更新。
请重启app完成更新， 
或点击下方“立即更新”安装最新版本。 
体验极速观影！',
            'ipadurl' => 'https://apps.apple.com/cn/app/id1546969964',
            'is_detail_stop' => 0,
            'detail_stop_time' => 5,
            'detail_stop_neirong' => '温馨提示： 
系统检测到当前app有新的更新。
点击下方“立即更新”安装最新版本。 
体验极速观影！',
            'heimingdan_jumpshengshi' => $disabledAreas,
            'heimingdaniosurl' => '-',
            'heimingdanshengshi' => $disabledAreas,
            'heimingdanipadurl' => '-',
            'heimingdananzhuourl' => '-',
        );
        $shebeidata = Db::name('device')->where(['device_id' => $device_id, 'app_id' => $app_id])->field('is_need_updated,first_ip,ip')->find();
//        dump($shebeidata);
        if (empty($shebeidata)) {
            $shebeidata['is_need_updated'] = 0;
        } else {
            $ip = $shebeidata['first_ip'];
            if (empty($ip)) {
                $firstLog = db('state')->where('device_id', $device_id)->order('time_added', 'asc')->field('ip')->find();
//            dump(db('state')->getLastSql());
//            dump($firstLog);
                if (!empty($firstLog)) {
                    //有观影记录第一次ip记录使用第一次访问的IP记录
                    $firstIp = $firstLog['ip'];
                } else {
                    //没有过观影记录那么 就是当前IP
                    $firstIp = $shebeidata['ip'];;
                }
                \db('device')->where('device_id', $device_id)->where('can_jump', 0)->update([
                    'first_ip' => $firstIp
                ]);
                $ip = $firstIp;
            }
        }
        if (empty($ip)) {
            $ip = get_client_ip(0, true);
        }
//        $ip = '101.87.84.46';//上海市

//        $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
//        dump($ip);
        if ($res) {
            //ios检查ip地址信息
            if (!empty($input['system_type']) && $input['system_type'] == 'ios') {
                $ipInfo = $this->getIpInfo($ip, 'app/index/checkbanben2');
            } else {
                $ipInfo = false;
            }
//            dump($ipInfo);
            if (isset($ipInfo['success'])) {
                $ipInfo = $ipInfo['ipInfo'];
                $res['heimingdanshengshi'] = array_filter(explode(',', $res['heimingdanshengshi']));
                $needChangeurl = false;
                if (strtolower($ipInfo['guo_code']) !== 'cn') {
                    $needChangeurl = true;
                } elseif (!empty($ipInfo['shi']) || !empty($ipInfo['sheng'])) {
                    if (in_array($ipInfo['sheng'], $res['heimingdanshengshi']) || in_array($ipInfo['shi'], $res['heimingdanshengshi'])) {
                        $needChangeurl = true;
                    }
                }

                if ($needChangeurl) {
                    //替换跳转地址
                    if (!empty($res['heimingdaniosurl']))
                        $res['iosurl'] = $res['heimingdaniosurl'];
                    if (!empty($res['heimingdanipadurl']))
                        $res['ipadurl'] = $res['heimingdanipadurl'];
                    if (!empty($res['heimingdananzhuourl'])) {
                        $res['anzhuourl'] = $res['heimingdananzhuourl'];
                    }
                }
            }
            unset($res['heimingdanshengshi']);
            unset($res['heimingdaniosurl']);
            unset($res['heimingdanipadurl']);
            unset($res['heimingdananzhuourl']);
            unset($res['heimingdan_jumpshengshi']);
            unset($res['jpush_app_key']);
            unset($res['jpush_master_secret']);
            unset($res['can_push']);
            unset($shebeidata['first_ip']);
            unset($shebeidata['ip']);
            $data = ['data' => ['banben' => $res, 'shebeidata' => $shebeidata], 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
        exit;
    }

    public function checkbanben2()
    {
        $this->checkDisabledAppId();
        //和数据表做比对
        $input = input();
        $keyname = $input['keyname'];
        $device_id = $input['device_id'];
        $app_id = $input['app_id'];
        $res = Db::name('banben')->where(['keyname' => $keyname])->find();
        $shebeidata = Db::name('device')->where(['device_id' => $device_id, 'app_id' => $app_id])->field('is_need_updated,first_ip,ip')->find();
//        dump($shebeidata);
        if (empty($shebeidata)) {
            $shebeidata['is_need_updated'] = 0;
        } else {
            $ip = $shebeidata['first_ip'];
            if (empty($ip)) {
                $firstLog = db('state')->where('device_id', $device_id)->order('time_added', 'asc')->field('ip')->find();
//            dump(db('state')->getLastSql());
//            dump($firstLog);
                if (!empty($firstLog)) {
                    //有观影记录第一次ip记录使用第一次访问的IP记录
                    $firstIp = $firstLog['ip'];
                } else {
                    //没有过观影记录那么 就是当前IP
                    $firstIp = $shebeidata['ip'];;
                }
                \db('device')->where('device_id', $device_id)->where('can_jump', 0)->update([
                    'first_ip' => $firstIp
                ]);
                $ip = $firstIp;
            }
        }
        if (empty($ip)) {
            $ip = get_client_ip(0, true);
        }
//        $ip = '17.57.26.123';//apple
//            $ip = '99.240.128.168';//加拿大
//            $ip ='119.82.24.93';//  日本
//            $ip = '101.87.84.46';//上海市
//            $ip = '111.204.125.34';//北京市
//            $ip ='153.99.252.180';//江苏省
//        dump($ip);
        if ($res) {
            //ios检查ip地址信息
            if (!empty($input['system_type']) && $input['system_type'] == 'ios') {
                $ipInfo = $this->getIpInfo($ip, 'app/index/checkbanben2');
            } else {
                $ipInfo = false;
            }
//            dump($ipInfo);
            if (isset($ipInfo['success'])) {
                $ipInfo = $ipInfo['ipInfo'];
                $res['heimingdanshengshi'] = array_filter(explode(',', $res['heimingdanshengshi']));
                $needChangeurl = false;
                if (strtolower($ipInfo['guo_code']) !== 'cn') {
                    $needChangeurl = true;
                } elseif (!empty($ipInfo['shi']) || !empty($ipInfo['sheng'])) {
                    if (in_array($ipInfo['sheng'], $res['heimingdanshengshi']) || in_array($ipInfo['shi'], $res['heimingdanshengshi'])) {
                        $needChangeurl = true;
                    }
                }

                if ($needChangeurl) {
                    //替换跳转地址
                    if (!empty($res['heimingdaniosurl']))
                        $res['iosurl'] = $res['heimingdaniosurl'];
                    if (!empty($res['heimingdanipadurl']))
                        $res['ipadurl'] = $res['heimingdanipadurl'];
                    if (!empty($res['heimingdananzhuourl'])) {
                        $res['anzhuourl'] = $res['heimingdananzhuourl'];
                    }
                    if ($input['system_type'] !== 'ios') {
                        $res['anzhuourl'] = '';
                        $res['status'] = 2;
                    }
                }
            }
            unset($res['heimingdanshengshi']);
            unset($res['heimingdaniosurl']);
            unset($res['heimingdanipadurl']);
            unset($res['heimingdananzhuourl']);
            unset($res['heimingdan_jumpshengshi']);
            unset($res['jpush_app_key']);
            unset($res['jpush_master_secret']);
            unset($res['can_push']);
            unset($shebeidata['first_ip']);
            unset($shebeidata['ip']);
            $data = ['data' => ['banben' => $res, 'shebeidata' => $shebeidata], 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function checkbanben()
    {
        //和数据表做比对
        $input = input();
        $keyname = $input['keyname'];
        $res = Db::name('banben')->where(['keyname' => $keyname])->find();

        if ($res) {
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function checkvodjishu()
    {
        //和数据表做比对
        $input = input();
        $id = $input['id'];
        $fenji = (int)$input['fenji'];
        $res = Db::name('m3u8cache_log')->where(['vod_id' => $id])->find();

        $data = ['xugengxin' => 0];
        if (!empty($res)) {
            $len = $res['len'];
            if ($fenji > $len) {
                $data['xugengxin'] = (int)$fenji - (int)$len;
            }
        } else {
            $data['xugengxin'] = (int)$fenji;
            //若数据表无数据可以新增一个数据
            Db::name('m3u8cache_log')->insert([
                "vod_id" => $id,
                "len" => 0,
                "ctime" => time()
            ]);
        }

        echo json_encode($data);
    }

    public function iscunzaifile()
    {
        $input = input();
        $id = $input['id'];
        $name = $input['name'];
        $fenjiindex = $input['fenjiindex'];
        $index = $input['index'] + 1 + $fenjiindex;

        $file_url_hou = "/upload/m3u8/" . $id . "/" . $index . "_" . $name . ".m3u8";
        $file_url = $_SERVER['DOCUMENT_ROOT'] . $file_url_hou;

        if (file_exists($file_url)) {
            echo json_encode(['status' => 1]);
            exit;
        } else {
            echo json_encode(['status' => $file_url]);
            exit;
        }
    }

    public function mudata()
    {
        $ids = input("ids/a");
        // if(empty($page)) {
        //     $page = 1;
        // }
        // $ll = 1;
        // $limit = ($page - 1) * $ll;
        $v = Db::name('Vod')->where(['vod_id' => ["in", $ids]])->order("vod_id asc")->select();
        // $v = Db::name('Vod')->limit($limit, $ll)->order("vod_id asc")->select();
        foreach ($v as &$v2) {
            $v2['playNames'] = getPlayerNames();
        }

        echo json_encode($v);
    }

    public function down()
    {

    }

    public function savehaibao()
    {
        $input = input();

        cache("haibao_" . $input['vod_id'] . "_" . $input['count'], $input['haibao']);
    }

    public function getvodpic()
    {
        $input = input();
        $image_file = $input["pic"];
        $image_info = getimagesize($image_file);
        $base64_image_content = "data:{$image_info['mime']};base64," . base64_encode(file_get_contents($image_file));
        //echo json_encode(['d' => $base64_image_content]);
        $this->success("", ['haibao' => $base64_image_content]);
    }

    public function savehaibaoimg()
    {
        $input = input();
        $id = $input['vod_id'];
        $count = $input['count'];

        // 创建id目录
        $path = $_SERVER['DOCUMENT_ROOT'] . "/upload/haibao/" . $id;
        $file_url = $path . "/" . $id . '_' . $count . '.jpg';
        $haibao = 'http://' . $_SERVER['HTTP_HOST'] . "/upload/haibao/" . $id . "/" . $id . '_' . $count . '.jpg';

        if (file_exists($file_url)) {
            $this->success("", ['haibao' => $haibao]);
            exit;
        }

        //先清空整个目录，然后再重新创建
        $this->delDirAndFile($path, true);
        mkdir(iconv("UTF-8", "GBK", $path), 0777, true);

        $res = file_put_contents($file_url, base64_decode($input['haibao']));

        if ($res > 0) {
            $this->success("", ['haibao' => $haibao]);
        }
    }

    public function gethaibao()
    {
        $input = input();
        $v['haibao'] = cache("haibao_" . $input['vod_id'] . "_" . $input['len']);
        $this->success('操作成功', $v);
    }

    public function gethaibaoimg()
    {
        $input = input();
        $id = $input['vod_id'];
        $count = $input['len'];
        // 创建id目录
        $path = $_SERVER['DOCUMENT_ROOT'] . "/upload/haibao/" . $id;
        $file_url = $path . "/" . $id . '_' . $count . '.jpg';

        $haibao = '';
        if (file_exists($file_url)) {
            $haibao = 'http://' . $_SERVER['HTTP_HOST'] . "/upload/haibao/" . $id . "/" . $id . '_' . $count . '.jpg';
        }
        $this->success("", ['haibao' => $haibao]);
    }

    public function checkHwadnew()
    {

        $input = input();

        $keyname = $input['keyname'];
        if (!empty($keyname)) {
            $res = Db::name('guanggaonew')->where(["keyname" => $keyname])->find();
        }
        if ($res) {
            //检查是否开启广告 开启广告后 检查用户注册时长 广告开启 后如果用户为新用户，7天内仍不显示广告 7天数据库设置的
            if ($res['allstatus'] == 1 && !empty($input['app_id'])) {
                $deviceInfo = \db('device')->where('app_id', $input['app_id'])->where('device_id', $input['device_id'])->find();
                // 当设备表有值的时候判断 注册时间
                if (!empty($deviceInfo)) {
                    $needCheckTime = strtotime(date('Y-m-d', $deviceInfo['time_added']));
//                dump('得到用户时间',date('Y-m-d H:i:s',$needCheckTime));
                    $checkTime = strtotime('-' . $res['no_ad_days'] . " days", strtotime('today'));
//                dump('7天前的时间',date('Y-m-d H:i:s',$checkTime));
                    if ($checkTime < $needCheckTime) {
                        $res['allstatus'] = 0;
                    } elseif ($deviceInfo['time_expired'] > time()) {
                        $res['leiji'] = 0;
                    }
                } elseif ($res['no_ad_days'] > 0) {
                    //当设备表没有值的时候检查免广告天数是否大于0，大于0则本次免广告 因为下次开启时设备表已经有了值了
                    $res['allstatus'] = 0;
                }

            }
//            dump($res);
//            exit;
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function checkHwad()
    {

        $input = input();

//        $input['app_id']='A6158795457051';
//        $input['device_id']="038560B5-FD87-426B-B7F0-80B5709BD458";
//        $input['keyname']="damiyingshi";
        $keyname = $input['keyname'];
        if (!empty($keyname)) {
            $res = Db::name('guanggao')->where(["keyname" => $keyname])->find();
        }
        if ($res) {
//            $res['allstatus']=1;
//            dump($res);
            //检查是否开启广告 开启广告后 检查用户注册时长 广告开启 后如果用户为新用户，7天内仍不显示广告 7天数据库设置的
            if ($res['allstatus'] == 1 && !empty($input['app_id'])) {
                $deviceInfo = \db('device')->where('app_id', $input['app_id'])->where('device_id', $input['device_id'])->find();
                // 当设备表有值的时候判断 注册时间
                if (!empty($deviceInfo)) {
                    $needCheckTime = strtotime(date('Y-m-d', $deviceInfo['time_added']));
//                dump('得到用户时间',date('Y-m-d H:i:s',$needCheckTime));
                    $checkTime = strtotime('-' . $res['no_ad_days'] . " days", strtotime('today'));
//                dump('7天前的时间',date('Y-m-d H:i:s',$checkTime));
                    if ($checkTime < $needCheckTime) {
                        $res['allstatus'] = 0;
                    }
                } elseif ($res['no_ad_days'] > 0) {
                    //当设备表没有值的时候检查免广告天数是否大于0，大于0则本次免广告 因为下次开启时设备表已经有了值了
                    $res['allstatus'] = 0;
                }

            }
//            dump($res);
//            exit;
            $data = ['data' => $res, 'code' => 1];
            echo json_encode($data);
        } else {
            $data = ['data' => false, 'code' => 0];
            echo json_encode($data);
        }
    }

    public function checkHwlogin()
    {
        $ip = get_client_ip(0, true);
        $ipLast = get_client_ip();
        if (strpos($ip, '17.') === 0 || strpos($ipLast, '17.') === 0 || strpos($ip, '144.178.') === 0 || strpos($ipLast, '144.178.') === 0 || strpos($ip, '98.') === 0 || strpos($ipLast, '98.') === 0) {
            $data = ["loginStatus" => 0, "adStatus" => 0];
        } else {
            $data = ["loginStatus" => 1, "adStatus" => 1];
            // $version = input('version');
            // if(in_array($version,['0.0.28','0.0.33'])){//正式版本
            //     $data = ["loginStatus" => 1,"adStatus"=>1];
            // }
            // elseif(in_array($version,['00.01.07','00.01.05','0.0.0'])){//测试版本
            //     $data = ["loginStatus" => 1,"adStatus"=>1];
            // }
        }
        //0显示原app，1显示哈文影视
        $this->success('操作成功', $data);
    }

    public function index()
    {
        $this->success('操作成功', ['a' => 1, "c" => 3]);
    }

    public function getAdConfig()
    {
        $this->success('获取成功', config('maccms.extra'));
    }

    protected function dumText($text)
    {
        echo $text . "<br/>";
    }

    /**
     * @deprecated
     */
    public function rebuildCache()
    {
        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Headers: *');

        $list = file_get_contents(ROOT_PATH . 'tuijian.json');
        $list = json_decode($list, true);
        $jsonPath = ROOT_PATH . 'json/';
        if (!file_exists($jsonPath)) {
            mkdir($jsonPath, 0777, true);
        }
        $this->dumText("正在生成首页信息缓存");
        $homeData = $this->getHome($list);
        file_put_contents($jsonPath . 'Home.json', json_encode($homeData));
        $this->dumText('首页缓存大小为' . filesize($jsonPath . 'Home.json') . 'byte');
        $this->dumText("首页信息缓存成功");
        foreach ($homeData as $item) {
            if (in_array($item['name'], ['轮播图', '热播推荐'])) {
                continue;
            }
            // dump($item['name']);
            $this->createjson($item, $jsonPath);
        }
        $this->dumText("轮播图开始处理");
        //处理轮播
        $articlelunbo = \db('art')->where('art_status', 1)->where(
            'art_level',
            9
        )->field(
            '0 as is_vod,art_id as vod_id,art_jumpurl,art_pic as vod_pic,art_pic_thumb as vod_pic_thumb,art_pic_slide as vod_pic_slide,art_name as vod_name,art_blurb as vod_blurb, art_time as vod_time'
        )->order('vod_time desc')->select();
        $vodLunbo = \db('vod')->where('vod_status', 1)->where(
            'vod_level',
            9
        )->fieldRaw(
            '1 as is_vod,vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time'
        )->order('vod_time desc')->select();
        $lunboData = array_merge($articlelunbo, $vodLunbo);
        usort(
            $lunboData,
            function ($a, $b) {
                if ($a['vod_time'] == $b['vod_time']) {
                    return $a['is_vod'] == 0 ? -1 : 1;
                }
                return $a['vod_time'] < $b['vod_time'] ? -1 : 1;
            }
        );
        $list['推荐']['轮播图']['list'] = $lunboData;

        file_put_contents($jsonPath . $list['推荐']['轮播图']['fileName'], json_encode($list['推荐']['轮播图']));
        $this->dumText('轮播图缓存大小为' . filesize($jsonPath . $list['推荐']['轮播图']['fileName']) . 'byte');
        $this->dumText("轮播图处理结束");

        //处理热播推荐
        $this->dumText("热播推荐开始处理");
        $zuijindouzaikan = \db('vod')->where('vod_status', 1)->fieldRaw(
            'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time'
        )->where('vod_level', '<', 9)->order('vod_level desc,vod_year desc,vod_time desc')->limit(50)->select();
        $list['推荐']['热播推荐']['list'] = $zuijindouzaikan;

        file_put_contents($jsonPath . $list['推荐']['热播推荐']['fileName'], json_encode($list['推荐']['热播推荐']));
        $this->dumText('热播推荐缓存大小为' . filesize($jsonPath . $list['推荐']['热播推荐']['fileName']) . 'byte');
        $this->dumText("轮播图处理结束");
        //处理发现
        $this->rebuildFaxianCache();
    }

    function rebuildFaxianCache()
    {
        //先生成faxian.json
        $faxians = [];
        $this->dumText('开始处理发现索引json');
        $data = db('explore')->where('is_show', 1)->order('sort', 'asc')->order('time_added', 'desc')->order(
            'id',
            'desc'
        )->select();
        foreach ($data as $faxian) {
            $faxian['xilie_name'] = $faxian['name'];
            $faxian['xilie_content'] = $faxian['content'];
            $faxian['xilie_id'] = $faxian['id'];
            $faxian['vod_pic_slide'] = $faxian['fengmian'];
            //获取10条数据
            $faxian['list'] = db('explore_vod')->alias('ev')->join(
                '__VOD__ v',
                'v.vod_id=ev.vod_id',
                'LEFT'
            )->where(
                'ev.explore_id',
                $faxian['id']
            )->field(
                'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time'
            )->order('ev.sort', 'asc')->order('ev.time_added', 'desc')->order('ev.id', 'desc')->limit(
                0,
                10
            )->select();
            $faxians[] = $faxian;
            $this->dumText('开始处理' . $faxian['name'] . '所有视频数据');
            $listItem = db('explore_vod')->alias('ev')->join(
                '__VOD__ v',
                'v.vod_id=ev.vod_id',
                'LEFT'
            )->where(
                'ev.explore_id',
                $faxian['id']
            )->field(
                'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time'
            )->order('ev.sort', 'asc')->order('ev.time_added', 'desc')->order('ev.id', 'desc')->select();
            $this->dumText('开始写入' . $faxian['name'] . '的详细列表数据');
            file_put_contents(ROOT_PATH . 'json/exploredetail_' . $faxian['id'] . '.json', json_encode($listItem));
            $this->dumText('成功写入' . $faxian['name'] . '的详细列表数据');
        }
        // dump($faxians);
        $this->dumText('生成发现json');
        file_put_contents(ROOT_PATH . 'faxian.json', json_encode($faxians, JSON_UNESCAPED_UNICODE));
        $this->dumText('生成发现json成功！');
    }

    protected function createjson($item, $jsonPath)
    {
        $this->dumText("开始处理《" . $item['name'] . "》");
        $where = [];
        if (!empty($item['ids'])) {
            $where['vod_id'] = ['in', $item['ids']];
            $order = 'FIELD(`vod_id`, ' . implode(',', $item['ids']) . ')';
        } else {
            $order = '';
            if (isset($item['cateId']) && $item['cateId'] > 0) {
                $where['type_id|type_id_1'] = $item['cateId'];
            }
        }
        if (isset($item['keywords'])) {
            if (!empty($item['keywords']['actor'])) {
                $where['vod_actor'] = [
                    [
                        ['like', '%,' . $item['keywords']['actor'] . ',%'],
                        ['like', $item['keywords']['actor'] . ',%'],
                        ['like', '%,' . $item['keywords']['actor']],
                    ],
                    'or'
                ];
                $item['total'] = 100;
            }
        }
        // dump($where);
        if (empty($where['vod_actor']) && empty($where['vod_id'])) {
            $list = [
                'page' => 1,
                'pagecount' => 0,
                'limit' => 0,
                'total' => 0,
                'list' => []
            ];
        } else {
            // dump('where');
            // dump($where);

            $page = 1;
            $limit = 1;
            $start = 0;
            //            $field = 'vod_name,vod_pic,vod_pic_thumb,vod_area,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level';
            $addition = 0;
            $totalshow = 1;
            $total = count($item['ids']) ?: $item['total'];
            $list = listAppData(
                $where,
                $order,
                1,
                $total,
                0,
                'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class',
                0
            );
        }
        $list = json_encode($list);
        // dump($list);
        if (json_last_error() === JSON_ERROR_INF_OR_NAN) {
            $list = json_encode(unserialize(str_replace(['NAN;', 'INF;'], '0;', serialize($list))));
        }
        if (empty($list)) {
            $list = '{}';
        }
        file_put_contents($jsonPath . $item['fileName'], $list);
        $this->dumText('生成' . $jsonPath . $item['fileName'] . '完成');
        $this->dumText('《' . $item['name'] . '》缓存大小为' . filesize($jsonPath . $item['fileName']) . 'byte');
        $this->dumText("结束处理《" . $item['name'] . "》");
    }

    /**
     * 接口说明
     * app加载就调用次内容 存入app的db中 用于视频页面展示视频来源
     */
    public function getPlayerNames()
    {
        $playerNames = getPlayerNames();
        foreach ($playerNames as &$playerName) {
            unset($playerName['des']);
            unset($playerName['target']);
            unset($playerName['sort']);
            unset($playerName['ps']);
            unset($playerName['tip']);
            unset($playerName['parse']);
            $playerName['name'] = $playerName['show'];
        }

        $this->success('获取成功', $playerNames);
    }

    public function getServer()
    {
        $list = getVodServer();
        usort(
            $list,
            function ($a, $b) {
                if ($a['sort'] === $b['sort']) {
                    return 0;
                }
                return $a['sort'] > $b['sort'] ? 1 : -1;
            }
        );
        $this->success('获取成功', $list);
    }

    /**
     * @param false $return
     * @return false|mixed|string
     * @deprecated
     */
    public function getHome_old($return = false)
    {
        $list = file_get_contents(ROOT_PATH . 'tuijian.json');
        $list = json_decode($list, true);
        $list = $list['推荐'];
        $list = array_values($list);
        foreach ($list as &$item) {
            $where = [];
            if ($item['isCate']) {
                $where['type_id|type_id_1'] = $item['cateId'];
            }
            $where['vod_level'] = ['in', $item['vod_level']];
            $data = listAppData(
                $where,
                $item['order'],
                1,
                $item['limit'],
                0,
                'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class',
                0
            );
            $item = array_merge($item, $data);
        }

        if ($return) {
            return $list;
        }
        $this->success('获取成功！', $list);
    }

    protected function getHome($list)
    {
        $list = $list['推荐'];
        foreach ($list as $key => &$item) {
            if (in_array($item['name'], ['轮播图', '热播推荐'])) {
                continue;
            }
            if (!$item['isShow']) {
                unset($list[$key]);
                continue;
            }
            $where = [];
            //首页推荐位与分类ID没有任何关系

            if (isset($item['ids'])) {
                if ($item['name'] == '最新电视剧') {
                    //重启第二季,长安诺,谋局,平凡的荣耀,太古神王,亲爱的自己
                    $itemIdssss = [76684, 76483, 53912, 52072, 45205, 53914];
                    $where['vod_id'] = ['in', $itemIdssss];
                    $order = 'FIELD(`vod_id`, ' . implode(',', $itemIdssss) . ')';
                } else {
                    $where['vod_id'] = ['in', $item['ids']];
                    $order = 'FIELD(`vod_id`, ' . implode(',', $item['ids']) . ')';
                }
            } else {
                if (isset($item['cateId']) && $item['cateId'] > 0) {
                    $where['type_id|type_id_1'] = $item['cateId'];
                }
                $order = '';
            }
            if (isset($item['ids']) && empty($item['ids'])) {
                $data = [
                    'page' => 1,
                    'pagecount' => 0,
                    'limit' => 0,
                    'total' => 0,
                    'list' => []
                ];
            } else {
//                $where['vod_level'] = ['in', $item['vod_level']];
//                dump($where);exit;
                $data = listAppData(
                    $where,
                    $order,
                    1,
                    $item['limit'],
                    0,
                    'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class',
                    0
                );

                if (empty($item['ids'])) {
                    $data['total'] = $item['total'];
                }
            }
            $item = array_merge($item, $data);
        }
        //处理轮播
        $articlelunbo = \db('art')->where('art_status', 1)->where(
            'art_level',
            9
        )->limit($list['轮播图']['limit'])->field(
            '0 as is_vod,0 as is_faxian,art_id as vod_id,art_jumpurl,art_pic as vod_pic,art_pic_thumb as vod_pic_thumb,art_pic_slide as vod_pic_slide,art_name as vod_name,art_blurb as vod_blurb, art_time as vod_time'
        )->order('vod_time desc')->select();
        //从发现里面找到轮播
        $faxianLunbo = [];
//            foreach ($faxians as $faxian){
//                if($faxian['isLunbo']){
//                    $faxianLunbo[]=[
//                        "is_vod"=>0,
//                        "is_faxian"=>1,
//                        "vod_name"=>$faxian['name'],
//                        "vod_pic"=>'',
//                        "vod_pic_thumb"=>'',
//                        "vod_pic_slide"=>$faxian['vod_pic_slide'],
//                        "vod_blurb"=>$faxian['xilie_content'],
//                        "vod_remarks"=>'',
//                        "vod_id"=>$faxian['xilie_id'],
//                        "vod_level"=>0,
//                        "vod_actor"=>'',
//                        "vod_class"=>'',
//                    ];
//                }
//            }
        $lunboData = array_merge($articlelunbo, $faxianLunbo);

        $vodLunbo = \db('vod')->where('vod_status', 1)->where(
            'vod_level',
            9
        )->limit($list['轮播图']['limit'])->fieldRaw(
            '1 as is_vod,0 as is_faxian,vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time'
        )->order('vod_time desc')->select();
        $lunboData = array_merge($lunboData, $vodLunbo);
        usort(
            $lunboData,
            function ($a, $b) {
                if ($a['is_vod'] == 0 && $a['is_faxian'] == 0) {
                    return -1;
                }

                if ($a['is_vod'] == 0 && $a['is_faxian'] == 1) {
                    return -1;
                }


                return $a['vod_time'] < $b['vod_time'] ? 1 : -1;
            }
        );
        $list['轮播图']['list'] = $lunboData;
        $zuijindouzaikan = \db('vod')->where('vod_status', 1)->limit($list['热播推荐']['limit'])->fieldRaw(
            'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time'
        )->where('vod_level', '<', 9)->order('vod_level desc,vod_year desc,vod_time desc')->select();
        $list['热播推荐']['list'] = $zuijindouzaikan;
        $list = array_values($list);

        return $list;
    }

    public function fetchVodBase()
    {
        $request_id = input('request_id', 0, 'intval');
        if ($request_id < 0) {
            $request_id = 0;
        }
//            $list = Db::name('vod')->where(['vod_id' => ['>', $request_id]])->field(
//                'vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class'
//            )->limit(100)->select();

//            dump($list);
        $this->success('获取成功', []);
    }

    public function feedback()
    {
        $input = input();
        if (empty($input['text'])) {
            $this->error('请填写反馈内容');
        }
        if (empty($input['type'])) {
            $this->error('请选择反馈类型');
        }
        $device_id = $input['device_id'];
        if (empty($device_id)) {
            dingding_curl(
                [
                    "msgtype" => "text",
                    "text" => [
                        "content" => '[影视意见反馈 设备信息出错]' . json_encode($input, JSON_UNESCAPED_UNICODE),
                    ],
                    "at" => [
                        "isAtAll" => true
                    ]
                ]
            );
            $this->error('设备信息有误');
        } else {
            dingding_curl(
                [
                    "msgtype" => "text",
                    "text" => [
                        "content" => '[影视意见反馈]' . json_encode($input, JSON_UNESCAPED_UNICODE),
                    ],
                    "at" => [
                        "isAtAll" => true
                    ]
                ]
            );
        }
//            {"type":"播放问题",
//                "text":"WIFI播放也卡",
//                "contact":"1343145749",
//                "_ajax":1,
//                "jiami":-1,
//                "language":"zh-CN",
//                "app_version":"0.0.45",
//                "sys_version":"10",
//                "version":"1.3.63",
//                "system_type":"android",
//                "device_id":"51547ff9f8efe2ae",
//                "device_model":"V1824A",
//                "device_name":"vivo",
//                "ui_mode":"phone",
//                "operator":"中国联通",
//                "connection_type":"wifi",
//                "is_proxy":0
//            }
//        $insertArray = [
//            'app_version' => $input['app_version'],
//            'contact' => $input['contact'],
//            'time_added' => time(),
//            'content' => $input['text'],
//            'type' => $input['type'],
//            'device_id' => $input['device_id'],
//        ];
//        //保存数据库
//        $id = \db('feedback')->insertGetId($insertArray);

//        if ($id > 0)
//            $this->success('success');
//        else
        $this->error('数据出错！');
    }


    public function exploreNew()
    {
//            $list = file_get_contents(ROOT_PATH.'faxian.json');
//            $list = json_decode($list, true);
//            $this->success('获取成功', $list);

        $page = input('page', 0, 'intval');
        if ($page < 1) {
            $page = 1;
        }
        $type_id = input('type_id', 0, 'intval');
        if ($type_id < 1) {
            $type_id = 1;
        }
        $data = cache('ExploreNew_list_' . $type_id . '_page_' . $page);
//
        if (empty($data)) {
            $data = [];
            $faxians = [];
//            $this->dumText('开始处理发现索引json');
            $list = db('explore')->where('is_show', 1)->where('type_id', $type_id)->order('sort', 'asc')->order('time_added', 'desc')->order(
                'id',
                'desc'
            )->paginate(6);
            foreach ($list as $faxian) {
                $faxian['xilie_name'] = $faxian['name'];
                $faxian['xilie_content'] = $faxian['content'];
                $faxian['xilie_id'] = $faxian['id'];
                $faxian['vod_pic_slide'] = $faxian['fengmian'];
                //获取10条数据
                $faxian['list'] = db('explore_vod')->alias('ev')->join(
                    '__VOD__ v',
                    'v.vod_id=ev.vod_id',
                    'LEFT'
                )->where('v.vod_id', '>', 0)->where(
                    'ev.explore_id',
                    $faxian['id']
                )->field(
                    'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.image_down,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time'
                )->order('ev.sort', 'asc')->order('ev.time_added', 'desc')->order('ev.id', 'desc')->limit(
                    0,
                    10
                )->select();
                foreach ($faxian['list'] as &$litem) {
                    if ($litem['image_down'] > 0) {
                        $litem['vod_pic'] = 'http://7dfjeh.aojiasen.cn/cover/' . $litem['vod_id'] . '.jpg';
                    }
                }
                $faxians[] = $faxian;
            }
            $data['list'] = $faxians;
            $data['lastPage'] = $list->lastPage();
            $data['currentPage'] = $list->currentPage();
            $data['listRows'] = $list->listRows();
            cache('ExploreNew_list_' . $type_id . '_page_' . $page, $data, 1200);
        }
        $this->success('获取成功', $data);
    }

    public function exploreDetailNew()
    {
        $id = input('xilie_id');
        $page = input('page', 0, 'intval');
        if ($page < 1) {
            $page = 1;
        }
//            $fileName = ROOT_PATH.'json/exploredetail_'.$id.'.json';
//            if (!file_exists($fileName)) {
//                $this->error('数据有误！');
//            }
        $data = cache('ExploreNew_detail_xilie_' . $id . '_page_' . $page);
        if (empty($data)) {
            $listItem = db('explore_vod')->alias('ev')->join(
                '__VOD__ v',
                'v.vod_id=ev.vod_id',
                'LEFT'
            )->where('v.vod_id', '>', 0)->where(
                'ev.explore_id',
                $id
            )->field(
                'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.image_down,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time'
            )->order('ev.sort', 'asc')->order('ev.time_added', 'desc')->order('ev.id', 'desc')->paginate(20);
//            dump(\db('explore_vod')->getLastSql());
            $data = [];
            $data['list'] = $listItem->items();
            foreach ($data['list'] as &$litem) {
                if ($litem['image_down'] > 0) {
                    $litem['vod_pic'] = 'http://7dfjeh.aojiasen.cn/cover/' . $litem['vod_id'] . '.jpg';
                }
            }
            $data['lastPage'] = $listItem->lastPage();
            $data['currentPage'] = $listItem->currentPage();
            $data['listRows'] = $listItem->listRows();
            cache('ExploreNew_detail_xilie_' . $id . '_page_' . $page, $data, 1200);
        }
//            dump($list);
        $this->success('获取成功', $data);
    }

    public function getExploreTypes()
    {
        $list = \db('explore_type')->where('is_show', 1)->order('sort', 'asc')->select();
        $this->success('获取成功！', $list);
    }

    public function tuijianNew()
    {
        $page = input('page', 0, 'intval');
        if ($page < 1) {
            $page = 1;
        }

        $data = cache('TuijianNew_list_page_' . $page);
        if (empty($data)) {
            $tuijians = [];
//            $this->dumText('开始处理发现索引json');
            $list = db('recommend')->where('is_show', 1)->order('sort', 'asc')->order('time_added', 'desc')->order(
                'id',
                'desc'
            )->paginate(3);
//                dump($data);
            foreach ($list as $tuijian) {
                $tuijian['xilie_name'] = $tuijian['name'];
                $tuijian['xilie_content'] = $tuijian['content'];
                $tuijian['xilie_id'] = $tuijian['id'];
                $tuijian['vod_pic_slide'] = $tuijian['fengmian'];
                $tuijian['list'] = db('recommend_vod')->alias('rv')->join(
                    '__VOD__ v',
                    'v.vod_id=rv.vod_id',
                    'LEFT'
                )->where(
                    'rv.recommend_id',
                    $tuijian['id']
                )->where('v.vod_id', '>', 0)->field(
                    'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.image_down,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time,rv.sort_manual,rv.sort'
                )->order('rv.sort_manual', 'asc')->order('rv.sort', 'asc')->order('rv.time_added', 'desc')->order('rv.id', 'desc')->limit(
                    0,
                    $tuijian['limit']
                )->select();
                foreach ($tuijian['list'] as &$litem) {
                    if ($litem['image_down'] > 0) {
                        $litem['vod_pic'] = 'http://7dfjeh.aojiasen.cn/cover/' . $litem['vod_id'] . '.jpg';
                    }
                }
//                    dump($tuijian);
                $tuijians[] = $tuijian;
            }
            $data = [];
            $data['list'] = $tuijians;
            $data['lastPage'] = $list->lastPage();
            $data['currentPage'] = $list->currentPage();
            $data['listRows'] = $list->listRows();
            cache('TuijianNew_list_page_' . $page, $data, 1200);
        }
        $host = request()->host();
        if (in_array($host, ['127.0.0.1', 'www.hawen.online'])) {
            foreach ($data['list'] as &$dataListItem) {
                $dataListItem['xilie_name'] = "苹果用户商店搜索《千文影视》[支持iPad 视频秒播]\n安卓用户点击右上角分享下载新版本 [视频秒播]";
                $dataListItem['name'] = "苹果用户商店搜索《千文影视》 [支持iPad 视频秒播]\n安卓用户点击右上角分享下载新版本 [视频秒播]";
            }
        }

        $this->success('获取成功', $data);
    }

    public function tuijianDetailNew()
    {
        $id = input('xilie_id');
        $page = input('page', 0, 'intval');
        if ($page < 1) {
            $page = 1;
        }
//            $fileName = ROOT_PATH.'json/exploredetail_'.$id.'.json';
//            if (!file_exists($fileName)) {
//                $this->error('数据有误！');
//            }
        $data = cache('TuijianNew_detail_xilie_' . $id . '_page_' . $page);
        if (empty($data)) {
            $listItem = db('recommend_vod')->alias('rv')->join(
                '__VOD__ v',
                'v.vod_id=rv.vod_id',
                'LEFT'
            )->where(
                'rv.recommend_id',
                $id
            )->where('v.vod_id', '>', 0)->field(
                'v.vod_name,v.vod_pic,v.vod_pic_thumb,v.image_down,v.vod_pic_slide,v.vod_blurb,v.vod_remarks,v.vod_id,v.vod_level,v.vod_actor,v.vod_class,v.vod_time,rv.sort_manual,rv.sort'
            )->order('rv.sort_manual', 'asc')->order('rv.sort', 'asc')->order('rv.time_added', 'desc')->order('rv.id', 'desc')->paginate(20);
//            dump(\db('explore_vod')->getLastSql());

            $data = [];
            $data['list'] = $listItem->items();
            foreach ($data['list'] as &$litem) {
                if ($litem['image_down'] > 0) {
                    $litem['vod_pic'] = 'http://7dfjeh.aojiasen.cn/cover/' . $litem['vod_id'] . '.jpg';
                }
            }
            $data['lastPage'] = $listItem->lastPage();
            $data['currentPage'] = $listItem->currentPage();
            $data['listRows'] = $listItem->listRows();
            cache('TuijianNew_detail_xilie_' . $id . '_page_' . $page, $data, 1200);
        }
//            dump($list);
        $this->success('获取成功', $data);
    }


    public function getImageConfig()
    {
        $input = input('type', '', 'trim');
        if (empty($input)) {
            $input = 'player_image';
        }
        $data = \db('config')->where('name', 'player_image')->whereOr('name', 'vod_player_image')->column('value', 'name');
        $this->success('获取成功', $data);
    }

    public function getIpInfo($ip, $from)
    {
        $ipInfo = \db('ip')->where('ip', $ip)->find();
        if (empty($ipInfo)) {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId('cn-hangzhou')
                ->asDefaultClient();
            try {
                $result = AlibabaCloud::rpc()
                    ->product('geoip')
                    // ->scheme('https') // https | http
                    ->version('2020-01-01')
                    ->action('DescribeIpv4Location')
                    ->method('POST')
                    ->host('geoip.aliyuncs.com')
                    ->options([
                        'query' => [
                            'Ip' => $ip,
                        ],
                    ])
                    ->request();
                $resultArray = $result->toArray();

                $ipInfo = [
                    'ip' => $ip,
                    'x' => $resultArray['Longitude'],
                    'y' => $resultArray['Latitude'],
                    'sheng' => $resultArray['Province'],
                    'shi' => $resultArray['City'],
                    'guo' => $resultArray['Country'],
                    'guo_code' => $resultArray['Country'] == '局域网' ? 'other' : $resultArray['CountryCode'],
                    'from' => $from
                ];
                //新增
                try {
                    db('ip')->insert($ipInfo);
//                        dump('=====' . db('ip')->getLastSql());
                } catch (\Exception $e) {
                    db('ip')->where('ip', $ip)->update($ipInfo);
//                        dump('A ===' . db('ip')->getLastSql());

                }
            } catch (ClientException $e) {
//                echo $e->getErrorMessage() . PHP_EOL;
                return ['error' => $e->getErrorMessage()];
            } catch (ServerException $e) {
//                echo $e->getErrorMessage() . PHP_EOL;
                return ['error' => $e->getErrorMessage()];
            }
        }
        return ['success' => true, 'ipInfo' => $ipInfo];
    }
}